const inquirer = require('inquirer');
const fs = require('fs-extra');
const chalk = require('chalk');
const widgetDir = './src/extensions';
var shell = require('shelljs');



const firstLetterUpperCase = (word = '') => {
  return word.replace(/_/mg, '-').replace(/\b(\w)(\w*)/g, ($0, $1, $2) => {
    return $1.toUpperCase() + $2;
  }).replace(/-/mg, '');
};

const selectPublishComponents = async () => {
  const list = fs.readdirSync(widgetDir).filter(file => !/(\.ts|\.js|\.vue)$/.test(file));
  const ret = {};
  // const data = await inquirer.prompt([{
  //   type: 'checkbox',
  //   message: '请选择需要发布的二开组件!',
  //   name: 'widgets',
  //   choices: list,
  // }]);

  // if (data.widgets.length === 0) {
  //   console.log(chalk.red('请选择要编译的组件！！'));
  //   process.exit(1);
  // }

  const data = {
    widgets: list
  }

  data.widgets.forEach((widget) => {
    const widgetName = firstLetterUpperCase(widget);
    const importUrl = `${widgetDir}/${widget}/index.ts`;
    if (fs.existsSync(importUrl)) {
      ret[`./${widgetName}`] = {
        name: widgetName,
        import: `${widgetDir}/${widget}/index.ts`,
      };
    } else {
      console.log(`**${chalk.yellow(`组件${widgetName}缺少index.ts文件,此组件将不会编译`)}**`);
    }
  });

  return ret;
};

// 检测开发者写的组件中是否有版本信息、是否是规范的版本写法
// 返回[{path: '', widgetName: ''}]
// widgetVersion 没有写空字符串, 错误的写法就返回错误的写法
const checkWidgetVersion = (list) => {
  const ret = [];
  Object.values(list).forEach((widgetInfo) => {
    const content = fs.readFileSync(widgetInfo.import).toString()
      .replace(/\/\/\s\S+/gm, '').replace(/[\r\n\s'"]+/mg, '');
    const version = content.match(/version:\d+\.\d+\.\d+/im);
    if (!version) {
      ret.push({
        path: widgetInfo.import,
        name: widgetInfo.name,
      });
    }
  });
  return ret;
};

const patchWidgetVersion = async (widgetList) => {
  if (widgetList.length) {
    console.log(chalk.yellow('**下列选中的组件版本信息不完善,系统将自动修复版本信息**'));
    widgetList.forEach((widget) => {
      console.log(`**${chalk.yellow(`组件名称：${widget.name}`)}**`);
      const content = fs.readFileSync(widget.path).toString().replace(/export\s+default\s+{\n/, (regContent) => {
        return `${regContent}  version: '1.0.0',\n`;
      });
      fs.writeFileSync(widget.path, content);
    });
    console.log(`**${chalk.green('版本信息修复完成,组件开始编译...')}**`);
  }
};

/*
  生成入口文件entries.json
*/
const generateEntries = (list, name) => {
  const targetFolder = './desk/extensions/route';
  const entries = [];
  Object.keys(list).forEach(key => {
    entries.push({
      module: key,
      appName: name,
      name: list[key].name,
    });
  })
  const entriesFile = targetFolder + '/entries.json';
  fs.writeJSONSync(entriesFile, entries, { spaces: 2 });
}

(async () => {
  // const list = await selectPublishComponents();
  // patchWidgetVersion(checkWidgetVersion(list));
  // const data = fs.readJSONSync('./exposes/config.json');
  // Object.keys(list).forEach(key => {
  //   fs.emptyDirSync('./dist'); // 清空dist,以防止多组件打包文件混杂
  //   data.exposes = {};
  //   data.exposes[key] = list[key];
  //   fs.writeJSONSync('./exposes/config.json', data, { spaces: 2 });
  //   shell.exec('npm run buildc');
  // });
  shell.exec('npm run buildc');
  // generateEntries(list, data.name);
  process.exit(0);
})();